/************** O T T R   C O P Y R I G H T   N O T I C E **************
 **                                                                   **
 ** © 2013 OTTR, Inc.  All rights reserved.                           **
 **                                                                   ** 
 *************** O T T R   C O P Y R I G H T   N O T I C E *************/

package com.jonathan.javatar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author Jonathan Paz <jonathan.paz@ottr.com>
 */
public class TarInputStream extends BufferedInputStream {
    private boolean closed;
    private boolean entryEOF;

    public TarInputStream(InputStream in) {
        super(in,10240);
    }

    public TarInputStream(InputStream in, int size) {
        super(in,size);
        if ((size % 512) != 0) {
            throw new IllegalArgumentException("size must be a multiple of 512");
        }
    }

    private void ensureOpen() throws IOException {
        if (closed) {
            throw new IOException("The stream is closed");
        }
    }

    public TarEntry getNextEntry() throws IOException {
        ensureOpen();
        return null;
    }

    public void closeEntry() throws IOException {
        ensureOpen();
        // get to end of entry
        entryEOF = true;
    }

    @Override
    public int available() throws IOException {
        ensureOpen();
        if (entryEOF) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (available() >= 1) {
            return read(b, off, len);
        } else {
            return -1;
        }
    }

    @Override
    public long skip(long n) throws IOException {
        return super.skip(n); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void close() throws IOException {
        if (!closed) {
            super.close(); //To change body of generated methods, choose Tools | Templates.
            closed = true;
        }
    }

}
